package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.CartItemRequest;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.ShoppingCart;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.CartService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/cart")
@Tag(name = "购物车模块")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService userService;

    // ==================== 模块二：购物车模块增强新增接口 ====================

    @Operation(summary = "更新购物车商品数量")
    @PutMapping("/update/{id}")
    public Result<?> updateCartItemQuantity(
            @Parameter(description = "购物车项ID") @PathVariable Long id,
            @RequestBody UpdateQuantityRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = cartService.updateCartItemQuantity(id, user.getId(), request.getQuantity());
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新购物车数量失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "清空购物车")
    @DeleteMapping("/clear")
    public Result<?> clearCart() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = cartService.clearCart(user.getId());
            return success ? Result.success("清空成功") : Result.error("清空失败");
        } catch (Exception e) {
            log.error("清空购物车失败", e);
            return Result.error("清空失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量添加到购物车")
    @PostMapping("/batch-add")
    public Result<?> batchAddToCart(@RequestBody List<CartItemRequest> requests) {
        try {
            if (requests == null || requests.isEmpty()) {
                return Result.error("请求参数不能为空");
            }

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 转换为ShoppingCart对象
            List<ShoppingCart> cartItems = requests.stream()
                    .map(req -> {
                        ShoppingCart cart = new ShoppingCart();
                        cart.setProductId(req.getProductId());
                        // 转换productType: String -> Integer (1-宠物, 2-商品)
                        Integer productType = convertProductType(req.getProductType());
                        if (productType == null) {
                            throw new IllegalArgumentException("商品类型无效，应为1（宠物）或2（商品）");
                        }
                        cart.setProductType(productType);
                        cart.setQuantity(req.getQuantity());
                        return cart;
                    })
                    .collect(Collectors.toList());

            boolean success = cartService.batchAddToCart(cartItems, user.getId());
            return success ? Result.success("批量添加成功") : Result.error("批量添加失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("批量添加购物车失败", e);
            return Result.error("批量添加失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取购物车商品总数")
    @GetMapping("/count")
    public Result<Integer> getCartCount() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Integer count = cartService.getCartCount(user.getId());
            return Result.success("获取成功", count);
        } catch (Exception e) {
            log.error("获取购物车总数失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    // ==================== 原有接口 ====================

    @Operation(summary = "将商品加入购物车")
    @PostMapping("/add")
    public Result<?> addToCart(@RequestBody ShoppingCart cart) {
        try {
            // 获取当前用户ID
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            cart.setUserId(user.getId());
            
            // 如果productType为空，默认设置为2（商品）
            if (cart.getProductType() == null) {
                cart.setProductType(2);
            }
            
            boolean success = cartService.addToCart(cart);
            return success ? Result.success("添加成功") : Result.error("添加失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("添加购物车失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询当前用户的购物车内容")
    @GetMapping("/list")
    public Result<List<ShoppingCart>> getCartList() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            List<ShoppingCart> cartList = cartService.getCartList(user.getId());
            return Result.success(cartList);
        } catch (Exception e) {
            log.error("查询购物车失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "从购物车中移除商品")
    @DeleteMapping("/remove/{id}")
    public Result<?> removeFromCart(
            @Parameter(description = "购物车项ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = cartService.removeFromCart(id, user.getId());
            return success ? Result.success("移除成功") : Result.error("移除失败");
        } catch (Exception e) {
            log.error("移除购物车失败", e);
            return Result.error("移除失败: " + e.getMessage());
        }
    }

    @Data
    public static class UpdateQuantityRequest {
        private Integer quantity;
    }

    /**
     * 转换商品类型：String -> Integer
     * @param productType 商品类型字符串 ("1", "2", "宠物", "商品")
     * @return Integer类型 (1-宠物, 2-商品)
     */
    private Integer convertProductType(String productType) {
        if (productType == null || productType.trim().isEmpty()) {
            return null;
        }
        String trimmed = productType.trim();
        // 支持数字字符串
        if ("1".equals(trimmed) || "宠物".equals(trimmed)) {
            return 1;
        } else if ("2".equals(trimmed) || "商品".equals(trimmed)) {
            return 2;
        }
        // 尝试解析为整数
        try {
            int type = Integer.parseInt(trimmed);
            if (type == 1 || type == 2) {
                return type;
            }
        } catch (NumberFormatException e) {
            // 忽略解析错误
        }
        return null;
    }
}
